import pandas as pd
import matplotlib.pyplot as plt
import pymongo
from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator
import numpy as np
import jieba
import re

import api

class DealwithData(object):
    def __init__(self):
        config = api.Config()
        self.mongo_url = config.get('db', 'MONGO_URL')
        self.mongo_db = config.get('db', 'MONGO_DB')
        self.mongo_set_danmu = config.get('db', 'MONGO_SET_DANMU')
        self.mongo_set_gift = config.get('db', 'MONGO_SET_GIFT')
        self.mongo_set_noble = config.get('db','MONGO_SET_NOBLE')
        self.myset_danmu = None
        self.myset_gift = None
        self.myset_noble = None
        self.gift = None
        self.danmu = None
        #self.word_list = []#中文停词库

    def init_data(self):
        client = pymongo.MongoClient(self.mongo_url)
        db = client[self.mongo_db]
        self.myset_danmu = db[self.mongo_set_danmu]
        self.myset_gift = db[self.mongo_set_gift]
        self.myset_noble = db[self.mongo_set_noble]

        self.read_from_db()#加载数据库数据
        #self.get_stop_word()#加载中文停词库

    def get_stop_word(self,filepath='中文停用词库.txt'):
        word_list = []
        for line in open(filepath, 'r'):
            word_list.append(line.strip())
        return word_list

    def read_from_db(self):
        query = self.myset_gift.find()
        df = pd.DataFrame(list(query))
        self.gift = df.loc[:,['roomid','sn','dn','gn','gc']]

        query = self.myset_danmu.find()
        self.danmu = pd.DataFrame(list(query))
        # print(self.danmu)
        #print(self.gift.head(5))

    def draw_danmu_ciyun(self):
        self.danmu['word'] = self.danmu['content'].apply(self.deal_content)
        word_dict = self.get_word_dict(self.danmu['word'])  # 统计词频
        self.word_cloud_description(word_dict)  # 根据词频，绘制词云图

    def deal_content(self,content):
        # 进行结巴分词
        seg_list = jieba.cut(content)
        word_list = '/'.join(seg_list).split('/')
        # 剔除词的list
        #li = ['MM', '黄图', '.', '']
        li = []
        stop_word = self.get_stop_word()
        word_li = []
        for word in word_list:
            word = word.strip().upper()
            if re.match(r'6+$',word):
                word = '666666'
            elif re.match(r'(Q+$)|群|扣',word):
                word = 'QQ'
            if word not in stop_word and word not in word_li and word != '' and word not in li:
                word_li.append(word)
        return word_li

    # 统计词频
    def get_word_dict(self,series):
        word_dict = {}
        for word_list in list(series):
            for word in word_list:
                # 如果在字典里面就+1
                if word in word_dict:
                    word_dict[word] += 1
                # 如果不在字典里面，就初始化为1
                else:
                    word_dict[word] = 1
        # df = pd.Series(word_dict)
        # df.to_csv('data/cipin.csv',encoding='gb18030')
        return word_dict

    # 根据词频，进行词云统计
    def word_cloud_description(self,word_dict):
        # 背景图片，用来限制显示的形状
        backgroud = plt.imread('5.jpg')
        # 实例化词云对象
        wc = WordCloud(
            # background_color='SaddleBrown',
            background_color='white',  # 背景颜色
            mask=backgroud,  # 背景图片
            font_path='C:\Windows\Fonts\msyh.ttf',  # 如果为中文，需要添加该路径
            max_words=1000,  # 设置最大实现的次数
            stopwords=STOPWORDS,  # 停用词
            max_font_size=100,  # 最大字体大小
            random_state=30  # 设置有多少种随机生成状态，即有多少种配色方案
        )
        wc.generate_from_frequencies(word_dict)  # 传入词频
        img_colors = ImageColorGenerator(backgroud)
        # wc.recolor(color_func=img_colors)
        plt.figure(figsize=(10, 8))
        plt.imshow(wc)  # 显示词云图
        plt.axis('off')  # 取出坐标轴
        plt.savefig('saywhat4.png', dpi=400, bbox_inches='tight')  # 保存

    #绘制礼物榜前10
    def draw_gift_top10(self):
        plt.rcParams['font.sans-serif'] = ['KaiTi']
        fig = plt.figure(figsize=(8, 5))
        self.gift['dn'].value_counts(ascending=True).tail(10).plot(kind='barh')
        data = self.gift['dn'].value_counts(ascending=True).tail(10)
        x = list(data.values)
        y = list(range(len(data.index)))

        for a, b in zip(x, y):
            plt.text(a+2, b, str(a), ha='center', va='bottom', fontsize=12)
        plt.xlim(0, 100)
        plt.yticks(list(range(len(data.index))), data.index,rotation=30, fontsize=10)
        plt.title('主播礼物榜前10', fontsize=20)
        plt.savefig('gift10.png', dpi=300, bbox_inches='tight')

    def money(self,data):
        if '火箭' == data or '空投补给箱'== data:
            return 500
        elif '超级火箭' == data:
            return  2000
        else:
            return 0

    #绘制金钱榜前10
    def draw_money_top10(self):
        plt.rcParams['font.sans-serif'] = ['KaiTi']
        fig = plt.figure(figsize=(8, 5))
        self.gift['money'] = self.gift['gn'].apply(self.money)
        self.gift.groupby('dn')['money'].sum().sort_values(ascending=True)[-10:].plot(kind='barh')
        money = self.gift.groupby('dn')['money'].sum().sort_values(ascending=True)[-10:]

        x = list(money.values)
        y = list(range(len(money.index)))
        for a, b in zip(x, y):
            plt.text(a+100, b, str(a), ha='left', va='bottom', fontsize=12)
        # plt.xlim(0, 200000)
        plt.yticks(list(range(len(money.index))), money.index,rotation=30, fontsize=10)
        plt.ylabel('',fontsize=15)
        plt.xlabel('￥',fontsize=15)
        plt.title('主播金钱榜前10', fontsize=20)
        plt.savefig('money10.png',dpi=300,bbox_inches='tight')

    # 绘制土豪榜前10
    def draw_donate_top10(self):
        plt.rcParams['font.sans-serif'] = ['KaiTi']
        fig = plt.figure(figsize=(8, 5))
        self.gift['money'] = self.gift['gn'].apply(self.money)
        self.gift.groupby('sn')['money'].sum().sort_values(ascending=True)[-10:].plot(kind='barh')
        money = self.gift.groupby('sn')['money'].sum().sort_values(ascending=True)[-10:]

        x = list(money.values)
        y = list(range(len(money.index)))
        for a, b in zip(x, y):
            plt.text(a+100, b, str(a), ha='left', va='bottom', fontsize=12)
        # plt.xlim(0, 200000)
        plt.yticks(list(range(len(money.index))), money.index,rotation=30, fontsize=10)
        plt.ylabel('',fontsize=15)
        plt.xlabel('￥',fontsize=15)
        plt.title('土豪金钱榜前10', fontsize=20)
        plt.savefig('richer10.png',dpi=300,bbox_inches='tight')

if __name__ == '__main__':
    deal = DealwithData()
    deal.init_data()
    # deal.draw_gift_top10()
    #deal.draw_money_top10()
    #deal.draw_donate_top10()
    deal.draw_danmu_ciyun()